package com.xpp.yanpicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.xpp.yanpicturebackend.annotation.AuthCheck;
import com.xpp.yanpicturebackend.common.BaseResponse;
import com.xpp.yanpicturebackend.common.ResultUtils;
import com.xpp.yanpicturebackend.constant.UserConstant;
import com.xpp.yanpicturebackend.exception.BusinessException;
import com.xpp.yanpicturebackend.exception.ErrorCode;
import com.xpp.yanpicturebackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;

    /**
     * 测试文件上传功能(仅管理员可用)
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/test/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        // 指定文件目录
        String filePath = String.format("/test/%s", originalFilename);
        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = File.createTempFile(filePath, null);
            // 存储到临时文件中
            multipartFile.transferTo(tempFile);
            // 上传到 COS
            cosManager.putObject(filePath, tempFile);
            // 返回可访问的地址
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            boolean delete = tempFile.delete();
            if (!delete) {
                log.error("file delete error,filepath = {}", filePath);
            }
        }
    }


    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream objectContent = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            objectContent = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(objectContent);
            response.setContentType("application/octet-steam;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            // 关闭流
            if (objectContent == null) {
                objectContent.close();
            }
        }
    }
}
